package com.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.user.common.R;

import com.user.config.RandomUtil;
import com.user.mapper.UserMapper;
import com.user.service.MSGService;
import com.usian.model.shop.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/JWTTest")
public class MSGController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MSGService jwtService;
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/send")
    public R send(String phone) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if (user == null) {
            return R.error("手机号不存在");
        }
        // 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.success("验证码获取成功");
        }
        // 如果redis获取不到，进行阿里云发送
        code = RandomUtil.getFourBitRandom();//生成随机数
        Map map = new HashMap();
        map.put("code", code);
        boolean b = jwtService.send(map, phone);
        if (b) {
            //如果发送成功，就把验证码存到redis里，设置5分钟有效时间
            redisTemplate.opsForValue().set("yanzheng", code, 5000, TimeUnit.MINUTES);
            System.out.println("succeed");
            System.out.println("验证码为" + code);
            return R.success("验证码发送成功");
        } else {
            System.out.println("fail");
            return R.error("验证码发送失败");
        }
    }


    @GetMapping("/save")
    public R save(String phone) {

        // 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.success("验证码获取成功");
        }
        // 如果redis获取不到，进行阿里云发送
        //生成随机数
        code = RandomUtil.getFourBitRandom();
        Map map = new HashMap();
        map.put("code", code);
        boolean b = jwtService.send(map, phone);
        if (b) {
            //如果发送成功，就把验证码存到redis里，设置5分钟有效时间
            redisTemplate.opsForValue().set("yanzheng", code, 5000, TimeUnit.MINUTES);
            System.out.println("succeed");
            System.out.println("验证码为" + code);
            return R.success("验证码发送成功");
        } else {
            System.out.println("fail");
            return R.error("验证码发送失败");
        }

    }
}

